package org.iipg.service.core.component;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.diboot.core.util.ContextHelper;
import lombok.extern.slf4j.Slf4j;
import org.iipg.service.core.vo.LoadRecordsVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Author: zhuhy163@163.com Date: 2020/10/2
 */
@Slf4j
@Component
public class JSONLoader {

    @Value("${ph.data.base-package:org.iipg.common.data.entity}")
    public String basePackage;

    public void load(String fileName, String classBaseName, Map<String, Object> extProps) {
        // 读取json对象
        JSONArray array = JSONUtil.readJSONArray(new File(fileName), StandardCharsets.UTF_8);

        try {
            // 构造entity的类名
            String className = StrUtil.upperFirstAndAddPre(StrUtil.toCamelCase(classBaseName), basePackage + ".");
            LoadRecordsVo loadRecordsVo = new LoadRecordsVo();
            for (Object obj : array) {
                // 将json对象转换为entity实体
                Object bean = BeanUtil.toBean(obj, Class.forName(className));
                BeanUtil.copyProperties(extProps, bean);
                loadRecordsVo.addRecord(bean);
            }
            // 根据entity类名动态获取IService实例，这里使用了diboot的ContextHelper方法，
            // hutool的SpringUtil方法有时会返回null
            IService service = ContextHelper.getIServiceByEntity(Class.forName(className));

            // truncate
            QueryWrapper<Object> wrappers = Wrappers.query();
            for (String key : extProps.keySet()) {
                wrappers.eq(key, extProps.get(key));
            }
            service.remove(wrappers);

            // 批量加载数据
            service.saveBatch(loadRecordsVo.getRecords());
            log.info("load {} size {}", classBaseName, loadRecordsVo.getRecords().size());
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
    }

}
